const mongoose = require("mongoose");
//登录
const login = async ({ username, password }) => {
  const data = await mongoose
    .model("shop-users")
    .findOne({ username, password });
  return data;
};
//查询重复用户名
const check = async (username) =>
  await mongoose.model("shop-users").findOne({ username });
//注册
const reg = async ({
  username,
  password,
  role = false,
  address = "",
  phone = "",
}) => {
  const data = await mongoose
    .model("shop-users")
    .create({ username, password, role, address, phone });
  return data;
};
//获取用户列表
const getMsg = async (curPage = 1, eachPage = 3) => {
  const result = {
    curPage: ~~curPage,
    eachPage: ~~eachPage,
    total: 0,
    maxPage: 0,
    rows: [],
  };
  const usersMoudle = mongoose.model("shop-users");
  //总条数
  result.total = await usersMoudle.countDocuments();
  //总页数
  result.maxPage = Math.ceil(result.total / result.eachPage);
  result.rows = await usersMoudle
    .find()
    .skip((result.curPage - 1) * result.eachPage)
    .limit(result.eachPage)
    .sort({
      _id: -1,
    })
    .exec();
  return result;
};
//更新用户信息
const update = async (id, phone, address) =>
  await mongoose
    .model("shop-users")
    .findByIdAndUpdate({ _id: id }, { phone, address }, (err, ret) => {
      err ? console.log("失败", err) : console.log("成功");
    });

//新增用户
const addUser = async ({ username, password, role, address, phone }) => {
  const data = await mongoose
    .model("shop-users")
    .create({ username, password, role, address, phone });
  return data;
};

//查询用户
const search = async (username, curPage, eachPage) => {
  const result = {
    curPage: ~~curPage,
    eachPage: ~~eachPage,
    total: 0,
    maxPage: 0,
    rows: [],
  };
  const usersMoudle = mongoose.model("shop-users");

  //总页数
  result.maxPage = Math.ceil(result.total / result.eachPage);
  result.rows = await usersMoudle
    .find({
      username: {
        $regex: String(username),
      },
    })
    .skip((result.curPage - 1) * result.eachPage)
    .limit(result.eachPage)
    .sort({
      _id: -1,
    })
    .exec();
  //总条数
  result.total = result.rows.length;
  return result;
};

module.exports = { login, check, reg, getMsg, update, addUser, search };
